package com.tdk.common.executor

import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executor
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

class AppExecutor private constructor(
    private val mMainExecutor: MainThreadExecutor,
    private val scheduledExecutor: ScheduledExecutor
) {
    private val mIoExecutor: Executor

    init {
        val coreThread = Runtime.getRuntime().availableProcessors()
        val workThread = coreThread * 2
        mIoExecutor = ThreadPoolExecutor(coreThread, workThread, 60, TimeUnit.MILLISECONDS, LinkedBlockingQueue())
    }

    private class MainThreadExecutor : Executor {
        private val mainHandler = Handler(Looper.getMainLooper())
        override fun execute(command: Runnable) {
            mainHandler.post(command)
        }

        fun postDelay(runnable: Runnable?, delayTime: Int) {
            mainHandler.postDelayed(runnable!!, delayTime.toLong())
        }
    }

    /**
     * Do on main thread.
     *
     * @param runnable the runnable
     */
    fun doOnMainThread(runnable: Runnable) {
        mMainExecutor.execute(runnable)
    }

    fun postDelayOnMainThread(runnable: Runnable?, delayTime: Int) {
        mMainExecutor.postDelay(runnable, delayTime)
    }

    fun doOnWorkThread(runnable: Runnable?) {
        mIoExecutor.execute(runnable)
    }

    fun scheduledExecutor(): ScheduledExecutor {
        return scheduledExecutor
    }

    companion object {
        val instance = AppExecutor(
            MainThreadExecutor(),
            ThreadPoolScheduledExecutor()
        )
    }
}